﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BrokerBase.Lib.Policy;
using BrokerBase.Lib.Product;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;

namespace Broker.View.PolicyView
{

    public delegate void SchemePeriodActingChangedHandler(ISchemePeriodActing spa);
    /// <summary>
    /// SchemeDutyForm.xaml 的交互逻辑
    /// </summary>
    public partial class SchemeActingForm 
    {
        private ISchemeActing schemeActing;
        //private IList<string> insurantStates;
        //private IList<string> holderStates;
        private int ConfigFixRow;

        private DutyActingForm dutyDetailFrm;

        public event SchemePeriodActingChangedHandler SchemePeriodActingChanged;

        private bool isFreeEdition;

        public SchemeActingForm(ISchemeActing schemeActing)
        {
            InitializeComponent();
            this.schemeActing = schemeActing;

            isFreeEdition =!LibGlobal.IsActive;

            Loaded += new RoutedEventHandler(SchemeActingForm_Loaded);
            
        }

        void SchemeActingForm_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                ConfigFixRow = grdConfig.RowDefinitions.Count();
                GetStates();
                SetAuxConfigs();

                schemeActing.BeginYear = schemeActing.Scheme.BizDate.Year;

                if (isFreeEdition)
                {
                    HideData();
                    tblFooter.Text = "免费版无法查看收益数据!";
                    tblFooter.Foreground = Brushes.Red;
                }

                schemeActing.Calc();
                gvActing.ItemsSource = schemeActing.PeriodActings;

                if (gvActing.Items.Count > 0)
                {
                    gvActing.SelectedItem = gvActing.Items[0];
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message +Environment.NewLine+ ex.StackTrace, "错误提示");

            }
        }

        private void GetStates()
        {
            IList<string> insStates = new List<string>();

            IList<string> holderStates = new List<string>();

            foreach (var p in schemeActing.PolicyActings)
            {
                insStates = insStates.Union(p.Policy.Product.InsurantStates).ToList<string>();
                holderStates = holderStates.Union(p.Policy.Product.HolderStates).ToList<string>();
            }

            insStates.Insert(0, string.Empty);
            holderStates.Insert(0, string.Empty);

            cmbInsurantState.ItemsSource = insStates;
            cmbHolderState.ItemsSource = holderStates;

            cmbInsurantState.IsEnabled = insStates.Count > 1;
            cmbHolderState.IsEnabled = holderStates.Count>1;
           
        }

        private void HideData()
        {

            DataTemplate dataTemplate = Application.Current.Resources["FreeEditionDataTemplate"] as DataTemplate;

            ControlTemplate controlTemplate = Application.Current.Resources["FreeEditionDataControlTemplate"] as ControlTemplate;

            Telerik.Windows.Controls.GridViewColumn col = gvActing.Columns["colValue"] ;
            
            col.CellTemplate = dataTemplate;

            
            txtValue.Template = controlTemplate;
        }

        private void btnReCalc_Click(object sender, RoutedEventArgs e)
        {
            Calc();
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void cmbInsurantState_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string state = cmbInsurantState.SelectedItem as string;

            ISchemePeriodActing spa = grdDetail.DataContext as ISchemePeriodActing;

            if (spa != null)
            {
                Calc();
            }
            
        }

        private void cmbHolderState_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string state = cmbHolderState.SelectedItem as string;


            ISchemePeriodActing spa = grdDetail.DataContext as ISchemePeriodActing;

            if (spa != null)
            {
                Calc();
            }
        }

        private void SetAuxConfigs()
        {
            try
            {
                //grdConfig.RowDefinitions.Clear();

                int totalRow = grdConfig.RowDefinitions.Count;

                if(totalRow>ConfigFixRow)
                    grdConfig.RowDefinitions.RemoveRange(ConfigFixRow,totalRow-1);

                int row = ConfigFixRow;

                object obj = FindResource("STheme");

                foreach (IPolicyActing pa in schemeActing.PolicyActings)
                {
                    foreach (KeyValuePair<IAuxProperty, object> d in pa.AuxConfigs)
                    {
                        RowDefinition rowDef = new RowDefinition();
                        rowDef.Height = new GridLength(30);
                        grdConfig.RowDefinitions.Add(rowDef);

                        BuildAuxConfigUI(d, row);
                        row++;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示");
            }
        }

        private void ViewResult(ISchemePeriodActing spa)
        {

            grdResult.RowDefinitions.Clear();
            grdResult.Children.Clear();

            int row = 0;

            foreach (IPolicyPeriodActing ppa in spa.PolicyPeriodActings)
            {
                foreach (IDutyActing da in ppa.DutyActings)
                {
                    if (da.Value!=0 || !string.IsNullOrEmpty(da.Description))
                    {
                        RowDefinition rowDef = new RowDefinition();
                        rowDef.Height = new GridLength(30);
                        grdResult.RowDefinitions.Add(rowDef);

                        TextBlock tbkName = new TextBlock();
                        tbkName.Text = da.Duty.Name +":";

                        tbkName.HorizontalAlignment = HorizontalAlignment.Right;
                        tbkName.TextAlignment = TextAlignment.Right;

                        tbkName.SetValue(Grid.ColumnProperty, 0);
                        tbkName.SetValue(Grid.RowProperty, row);

                        TextBlock tbkValue = new TextBlock();
                        tbkValue.Height = 24;
                        

                        if (isFreeEdition)
                        {
                            tbkValue.TextAlignment = TextAlignment.Right;
                            tbkValue.Text = "*****";
                        }
                        else
                        {

                            if (da.Value !=0)
                            {
                                tbkValue.TextAlignment = TextAlignment.Right;
                                tbkValue.Text = da.Value.ToString("F2");
                            }
                            else
                            {
                                tbkValue.TextAlignment = TextAlignment.Left;
                                tbkValue.Text = da.Description;
                            }
                        }

                        tbkValue.SetValue(Grid.ColumnProperty, 1);
                        tbkValue.SetValue(Grid.RowProperty, row);

                        grdResult.Children.Add(tbkName);
                        grdResult.Children.Add(tbkValue);
                        row++;
                    }
                    
                }
            }
        }

        private Control BuildAuxConfigUI(KeyValuePair<IAuxProperty,object> auxc,int row)
        {
            Control result = null;

            TextBlock tbk = new TextBlock();
            tbk.Text = auxc.Key.Name + ":";
            tbk.HorizontalAlignment = HorizontalAlignment.Right;
            tbk.SetValue(Grid.ColumnProperty, 0);
            tbk.SetValue(Grid.RowProperty, row);


            grdConfig.Children.Add(tbk);

            if (auxc.Key.IsCollection)
            {
                
                RadComboBox cmb = new RadComboBox();
                cmb.Height = 24;
                cmb.DataContext = auxc.Key;
                cmb.ItemsSource = auxc.Key.ListItems;
                cmb.SelectedIndex = 0;
                
                cmb.SelectionChanged+=AuxConfig_SelectionChanged;
                
                result = cmb;
            }
            else
            {
                TextBox txt=new TextBox();

                txt.Height = 24;
                txt.DataContext = auxc.Key;
                txt.Text=auxc.Value.ToString();
                txt.IsReadOnly = ! auxc.Key.IsVariable;
                txt.LostFocus += txt_LostFocus;
                txt.KeyDown += txt_KeyDown;
                result = txt;
            }

            result.SetValue(Grid.ColumnProperty, 1);
            result.SetValue(Grid.RowProperty, row);
            
            result.Margin = new Thickness(5, 0, 0, 0);

            grdConfig.Children.Add(result);

            return result;
        }

        void txt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {

                TxtCalc(sender as TextBox);
                
            }
        }

        void  txt_LostFocus(object sender, RoutedEventArgs e)
        {
            TxtCalc(sender as TextBox);
        }

        private void TxtCalc(TextBox txt)
        {
            try
            {

                IAuxProperty aux = txt.DataContext as IAuxProperty;
                KeyValuePair<IAuxProperty, object> auxc = schemeActing.AuxConfigs.FirstOrDefault(p => p.Key == aux);


                if (txt.Text != auxc.Value.ToString())
                {
                    object v = null;
                    string msg = null;
                    bool sucess = AuxProperty.TryGetValueByType(txt.Text.Trim(), auxc.Key.DataType, out v, out msg);
                    if (sucess)
                    {
                        schemeActing.AuxConfigs[auxc.Key] = v;
                        Calc();
                    }
                    else
                    {
                        MessageBox.Show(msg);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示");
            }
        }

        private void AuxConfig_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RadComboBox cmb = sender as RadComboBox;
            IAuxProperty aux = (IAuxProperty)cmb.DataContext;

            schemeActing.AuxConfigs[aux] = cmb.SelectedItem;
            Calc();
        }


        private void Calc()
        {
            try
            {
                schemeActing.Calc();
                gvActing.Items.Refresh();

                if (gvActing.SelectedItem != null)
                {
                    ViewResult(gvActing.SelectedItem as ISchemePeriodActing);

                    if (SchemePeriodActingChanged != null)
                    {
                        ISchemePeriodActing spa = gvActing.SelectedItem as ISchemePeriodActing;
                        SchemePeriodActingChanged(spa);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示");
            }
        }

        private void btnClearState_Click(object sender, RoutedEventArgs e)
        {
            foreach (ISchemePeriodActing spa in schemeActing.PeriodActings)
            {
                spa.HolderStates.Clear();
                spa.InsurantStates.Clear();
            }

            Calc();
        }



        private void grdResult_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            ISchemePeriodActing spa=e.NewValue as ISchemePeriodActing;

            if (spa != null)
                ViewResult(spa);
        }

        private void btnDetail_Click(object sender, RoutedEventArgs e)
        {
            ViewDetail();
        }

        private void gvActing_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            ViewDetail();
        }

        private void ViewDetail()
        {
            ISchemePeriodActing spa = gvActing.SelectedItem as ISchemePeriodActing;

            if (spa != null)
            {
                if (dutyDetailFrm == null)
                {
                    dutyDetailFrm = new DutyActingForm(this,spa);
                }

                dutyDetailFrm.IsTopmost = true;
                dutyDetailFrm.Owner = this;
                dutyDetailFrm.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                dutyDetailFrm.Show();

                if (SchemePeriodActingChanged != null)
                {
                    SchemePeriodActingChanged(spa);
                }
            }
        }

        private void gvActing_SelectionChanged(object sender, SelectionChangeEventArgs e)
        {
            ISchemePeriodActing spa = gvActing.SelectedItem as ISchemePeriodActing;

            if (spa != null && SchemePeriodActingChanged !=null)
            {
                SchemePeriodActingChanged(spa);
            }
        }

    }

    public class RowStyleSelector : StyleSelector
    {
        public override Style SelectStyle(object item, DependencyObject container)
        {
            if (((GridViewRow)container).GridViewDataControl.Items.IndexOf(item) == 0)
            {
                Style style = new Style(typeof(GridViewRow));
                Setter setter = new Setter(GridViewRow.DetailsVisibilityProperty, Visibility.Visible);
                style.Setters.Add(setter);
                return style;
            }

            return new Style(typeof(GridViewRow));
        }
    }

}
